package com.sinosoft.hydra.um.taglib;

import cn.com.sinux.spring.commons.SpringUtils;
import com.sinosoft.hydra.um.domain.permission.SysOrganization;
import com.sinosoft.hydra.um.services.SysOrganizationService;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * <p>自定义taglib
 * @author oujianlin@sinosoft.co
 * @date 2014-12-19 13:19	
 **/
public class Functions {

	private static SysOrganizationService organizationService;

    public static boolean in(Iterable iterable, Object element) {
        if(iterable == null) {
            return false;
        }
        return CollectionUtils.contains(iterable.iterator(), element);
    }

    public static String principal(Session session) {
        PrincipalCollection principalCollection =
                (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);

        return (String)principalCollection.getPrimaryPrincipal();
    }

    public static String organizationName(String organizationId) {
        SysOrganization organization = getOrganizationService().findOne(organizationId);
        if(organization == null) {
            return "";
        }
        return organization.getOrgName();
    }
//    public static List<TreeNode> organizationTree() {
//    	List<TreeNode> organizationTree = getOrganizationService().queryOrganizationWithMemberTree();
//    	return organizationTree;
//    }
//    public static String organizationTreeAsString() {
//    	List<TreeNode> organizationTree = getOrganizationService().queryOrganizationWithMemberTree();
//        return JSONUtils.toJSONString(organizationTree);
//    }

    public static String organizationNames(Collection<String> organizationIds) {
        if(CollectionUtils.isEmpty(organizationIds)) {
            return "";
        }

        StringBuilder s = new StringBuilder();
        for(String organizationId : organizationIds) {
        	SysOrganization organization = getOrganizationService().findOne(organizationId);
            if(organization == null) {
                return "";
            }
            s.append(organization.getOrgName());
            s.append(",");
        }

        if(s.length() > 0) {
            s.deleteCharAt(s.length() - 1);
        }
        return s.toString();
    }
    

	public static SysOrganizationService getOrganizationService() {
		if (organizationService == null) {
			organizationService = SpringUtils.getBean(SysOrganizationService.class);
		}
		return organizationService;
	}
  
}

